package com.seleniummaster.jmeterjunit;
import static org.junit.Assert.*;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class LoginTest {
  private WebDriver driver;
    private String baseUrl;
    private boolean acceptNextAlert = true;
    private StringBuffer verificationErrors = new StringBuffer();  
  @Before
  public void setUp() throws Exception {
    //use Firefox driver
    driver = new FirefoxDriver();
    //use demo.mahara.org site for testing
      baseUrl = "http://demo.mahara.org";
      //timeout if site page does not load in 30 seconds
      driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
  }
  @After
  public void tearDown() throws Exception {
    //quit the test
    driver.quit();
      String verificationErrorString = verificationErrors.toString();
      if (!"".equals(verificationErrorString)) {
        fail(verificationErrorString);
      }
  }
  @Test
  public void test() throws InterruptedException {
    //navigate to base url
    driver.get(baseUrl + "/");
    //clear username filed
      driver.findElement(By.id("login_login_username")).clear();
      //enter user name
      driver.findElement(By.id("login_login_username")).sendKeys("student1");
      //clear password
      driver.findElement(By.id("login_login_password")).clear();
      //enter password
      driver.findElement(By.id("login_login_password")).sendKeys("Testing1");
      //click on submit button
      driver.findElement(By.id("login_submit")).click();
      //assert the Dashboard link text
      for (int second = 0;; second++) {
        if (second >= 60) fail("timeout");
        try { if (isElementPresent(By.linkText("Dashboard"))) break; } catch (Exception e) {}
        Thread.sleep(1000);
      }

      assertEquals("Dashboard", driver.findElement(By.linkText("Dashboard")).getText());
    }
  private boolean isElementPresent(By by) {
      try {
        driver.findElement(by);
        return true;
      } catch (NoSuchElementException e) {
        return false;
      }
    }

    private boolean isAlertPresent() {
      try {
        driver.switchTo().alert();
        return true;
      } catch (NoAlertPresentException e) {
        return false;
      }
    }

    private String closeAlertAndGetItsText() {
      try {
        Alert alert = driver.switchTo().alert();
        String alertText = alert.getText();
        if (acceptNextAlert) {
          alert.accept();
        } else {
          alert.dismiss();
        }
        return alertText;
      } finally {
        acceptNextAlert = true;
      }
    }
  }